package com.lw.leetcode.sort.b;

import java.util.Map;
import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA.
 * 870. 优势洗牌
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/10 17:06
 */
public class AdvantageCount {

    public int[] advantageCount(int[] nums1, int[] nums2) {
        int length = nums2.length;
        if (length < 2) {
            return nums1;
        }
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int i : nums1) {
            map.merge(i, 1, (a, b) -> a + b);
        }
        for (int i = 0; i < length; i++) {
            int value = nums2[i] + 1;
            Map.Entry<Integer, Integer> entry = map.ceilingEntry(value);
            if (entry == null) {
                entry = map.firstEntry();
            }
            nums1[i] = entry.getKey();
            Integer count = entry.getValue();
            if (count == 1) {
                map.remove(nums1[i]);
            } else {
                map.put(nums1[i], count - 1);
            }
        }
        return nums1;
    }

}
